package com.snake.driver;

import com.snake.WebDriverUtil;
import com.snake.bean.HfGoodDescription;
import com.snake.bean.HfGoods;
import com.snake.bean.HfTaobaoLink;
import com.snake.db.Demo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/5/4 0004.
 */

public class FqWebDriver {

    private static WebDriver driver;
    private static StringBuffer verificationErrors = new StringBuffer();

    public static void main(String[] args) throws InterruptedException {
        String browserDriverUrl = "E:\\chromedriver\\chromedriver.exe";// 浏览器驱动路径
        //启动chrome浏览器
        System.setProperty("webdriver.chrome.driver", browserDriverUrl);
        //取消 chrome正受到自动测试软件的控制的信息栏
        ChromeOptions options = new ChromeOptions();
        options.addArguments("disable-infobars");
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized"));
        options.addArguments("--test-type", "--start-maximized");

        driver = new ChromeDriver(options);
        //driver.manage().window().maximize();// 最大化浏览器
        //driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);//设置操作超时时长，该设置是全局性的，即所有操作都最长等待30s
        Demo taobaoGoodLinkDemo = new Demo();
        List<HfTaobaoLink> taobaoGoodLink = taobaoGoodLinkDemo.getGoodLinkUrl();
        Thread.sleep(10000);
        for (int n = 0; n < taobaoGoodLink.size(); n++) {
            Thread.sleep(1000);
            int shopId = taobaoGoodLink.get(n).getShopId();
            String goodUrl = taobaoGoodLink.get(n).getTaobaoGoodLink();
            driver.get(goodUrl);
           /* Actions action = new Actions(driver);
            action.keyDown(Keys.CONTROL).sendKeys("w").keyUp(Keys.CONTROL).sendKeys(Keys.NULL).perform();*/
            boolean xiajia = driver.getPageSource().contains("此宝贝已下架");
            boolean sorry = driver.getPageSource().contains("抱歉！页面无法访问");
            if (xiajia || sorry) {

            } else {

                //商品标题
                By jTitle = By.className("tb-main-title");
                String jTitleText = driver.findElement(jTitle).getText();

                //商品主图
                By jImgBooth = By.id("J_ImgBooth");
                String jImgBoothSrc = driver.findElement(jImgBooth).getAttribute("src");


                //商品价格 begin
                By jPromoPriceNum = By.id("J_PromoPriceNum");
                String taobaoPrice = "";
                int intFinalTaobaoPrice = 0;
                if (WebDriverUtil.elementExist(driver, jPromoPriceNum)) {
                    WebElement jPromoPriceNumElement = driver.findElement(jPromoPriceNum);
                    taobaoPrice = jPromoPriceNumElement.getText();
                    taobaoPrice = taobaoPrice.substring(1, taobaoPrice.length());
                    intFinalTaobaoPrice = (int) Double.parseDouble(taobaoPrice) * 100;
                } else {
                    By jStrPrice = By.id("J_StrPrice");
                    WebElement jStrPriceElement = driver.findElement(jStrPrice);
                    if (jStrPriceElement != null) {
                        taobaoPrice = jStrPriceElement.getText();
                        taobaoPrice = taobaoPrice.substring(1, taobaoPrice.length());
                        String betweenPrice = "";
                        if (taobaoPrice.contains("-")) {
                            betweenPrice = taobaoPrice.split("-")[1];
                            System.out.println("范围价格==》" + betweenPrice);
                        } else {
                            betweenPrice = taobaoPrice;
                        }

                        intFinalTaobaoPrice = (int) Double.parseDouble(betweenPrice) * 100;
                    }
                }
                //商品价格 end

                //店铺名称 begin
                By tbSellerName = By.className("tb-seller-name");
                String tbSellerNameText = "";
                if (WebDriverUtil.elementExist(driver, tbSellerName)) {
                    WebElement tbSellerNameElement = driver.findElement(tbSellerName);
                    tbSellerNameText = tbSellerNameElement.getText();
                }
                //店铺名称 end


                Document pageSource = Jsoup.parse(driver.getPageSource());

                //商品尺码
                StringBuffer size = new StringBuffer();
                By sizeAll = By.cssSelector("#J_isku > div > dl.J_Prop.J_TMySizeProp.tb-prop.tb-clear.J_Prop_measurement");
                if (WebDriverUtil.elementExist(driver, sizeAll)) {
                    By spanBy = By.tagName("span");
                    List<WebElement> sizeWebElementList = driver.findElement(sizeAll).findElements(spanBy);
                    for (int j = 0; j < sizeWebElementList.size(); j++) {
                        size.append(sizeWebElementList.get(j).getText());
                        if (j < (sizeWebElementList.size() - 1)) {
                            size.append(";");
                        }

                        System.out.println("有尺码==>" + sizeWebElementList.get(j).getText());
                    }
                }


                //颜色分类
                StringBuffer color = new StringBuffer();
                Elements elements = pageSource.getElementsByAttributeValue("class", "J_TSaleProp tb-img tb-clearfix");
                Elements span = elements.get(0).getElementsByTag("span");

                for (int m = 0; m < span.size(); m++) {
                    color.append(span.get(m).text());
                    if (m < (span.size() - 1)) {
                        color.append(";");
                    }

                    System.out.println("有颜色==>" + span.get(m).text());
                }

                //商品详情
                By goodDetail = By.id("J_SubWrap");

                Elements attributes = pageSource.getElementsByAttributeValue("class", "attributes-list");
                String htmlAttributes = attributes.get(0).html();
                Elements smallPicturesElements = pageSource.getElementById("J_UlThumb").getElementsByTag("img");
                StringBuffer smallPictures = new StringBuffer();
                for (int i = 0; i < smallPicturesElements.size(); i++) {
                    String img = smallPicturesElements.get(i).attr("data-src");
                    System.out.println("这是第" + i + "小图片==》" + img);
                    System.out.println("替换成大图");
                    smallPictures.append(img.replace("50x50", "400x400").concat("_.webp"));
                    if (i < (smallPicturesElements.size() - 1)) {
                        smallPictures.append(";");
                    }

                }

                // Thread.sleep(5000);
                //商品视频 begin
                String goodVideoSrc = "";
                By videoBy = By.className("tb-video");
                if (WebDriverUtil.elementExist(driver, videoBy)) {
                    Actions action = new Actions(driver);
                    WebElement webElement = driver.findElement(videoBy);
                    action.doubleClick(driver.findElement(By.xpath("//*[@id=\"detail\"]/div[1]/div[1]/div/div[1]/div[1]/div/div[2]/div/div[1]/button[2]"))).perform();

                     System.out.println("商品视频链接==>" + pageSource.outerHtml());
                    //   Elements goodVideoDiv = pageSource.getElementsByClass("lib-video vjs-has-paused");
                    // Elements goodVideo = goodVideoDiv.get(0).getElementsByTag("video");
                    // goodVideoSrc = goodVideo.get(0).attr("src");


                }
                //商品视频 end

                String goodDetailHTML = pageSource.selectFirst("#description").outerHtml();
                //System.out.println();
                //String goodDetailHtml = driver.findElement(goodDetail)
                //颜色太复杂
                //    By colorButton = By.className("J_TSaleProp tb-img tb-clearfix");
                //   String colorButtonText = driver.findElement(colorButton).getText();

                System.out.println("淘宝商品标题==>" + jTitleText);
                System.out.println("淘宝主图==>" + jImgBoothSrc);
                System.out.println("尺码==>" + size);
                System.out.println("颜色==>" + color);
                System.out.println("价格===>" + taobaoPrice);
                //  System.out.println("商品详情html代码===>" + goodDetailHTML);
                // System.out.println(colorButtonText);
                HfGoods hfGoods = new HfGoods();
                String[] urlParamters = goodUrl.split("&");
                long taobaoGoodId = 0;
                for (int i = 0; i < urlParamters.length; i++) {
                    System.out.println("参数==>" + urlParamters[i]);
                    if (urlParamters[i].contains("id")) {
                        taobaoGoodId = Long.valueOf(urlParamters[i].split("=")[1]);
                        System.out.println("淘宝商品id=====>" + taobaoGoodId);
                    }

                }

                hfGoods.setShopId(shopId);
                hfGoods.setShopName(tbSellerNameText);

             /*   String regEx = "[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher ma = p.matcher(jTitleText.substring(0, 6));
                if (ma.matches()) {
                    hfGoods.setProductNo(Integer.parseInt(ma.replaceAll("").trim()));
                }*/
                hfGoods.setTitle(jTitleText);
                hfGoods.setTaobaoPrice(intFinalTaobaoPrice);
                hfGoods.setSize(size.toString());
                hfGoods.setColor(color.toString());
                hfGoods.setInventory(100);
                hfGoods.setBigPicture(jImgBoothSrc);
                hfGoods.setSmallPicture(smallPictures.toString());
                hfGoods.setTaobaoLink(goodUrl);
                hfGoods.setTaoBaoGoodId(taobaoGoodId);
                int firtProductNoIndex = htmlAttributes.lastIndexOf("货号:");
                System.out.println("货号索引位置==>" + firtProductNoIndex);
                System.out.println("商品属性内容为==>" + htmlAttributes);
                String productNo = "";
                int price = 0;
                if (taobaoGoodLink.get(n).getDealType() == 1) {
                    System.out.println("减去店家的优惠" + intFinalTaobaoPrice);
                    price = intFinalTaobaoPrice - taobaoGoodLink.get(n).getReversePrice() * 100;
                } else if (taobaoGoodLink.get(n).getDealType() == 2) {
                    System.out.println("除店家的优惠" + intFinalTaobaoPrice);
                    price = intFinalTaobaoPrice / taobaoGoodLink.get(n).getReversePrice();
                }
                //如果详情中不存在货号，则去标题找货号
                if (firtProductNoIndex <= 0) {
                    System.out.println("商品详情无货号=====》");
                    int titleProductNoIndex = jTitleText.lastIndexOf("#");
                    System.out.println("商品标题中有货号");
                    if (titleProductNoIndex > 0) {
                        System.out.println("货号在标题前面或中间");
                        System.out.println("总长度====>>" + jTitleText.length());
                        if (isNumeric(jTitleText.substring(0, 1))) {
                            productNo = jTitleText.substring(0, 5);
                        } else {
                            productNo = jTitleText.substring(titleProductNoIndex - 5, titleProductNoIndex);
                        }

                    } else {
                        System.out.println("货号在最后面");
                        productNo = jTitleText.substring(jTitleText.length() - 4, jTitleText.length());
                    }

                } else {
                    System.out.println("在商品详情中找到了货号=====》");
                    //商品详情中存在货号
                    productNo = htmlAttributes.substring(firtProductNoIndex + 9, firtProductNoIndex + 16);
                }

                String regEx = "[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(productNo);
                productNo = m.replaceAll("").trim();

                hfGoods.setAssembleAddress(taobaoGoodLink.get(n).getShopAddress() + "-" + productNo + "-" + String.valueOf(Double.valueOf(price / 100)));
                System.out.println("档口地址=====>" + taobaoGoodLink.get(n).getShopAddress());
                System.out.println("档口批发价====>" + price);


                hfGoods.setWholesalePrice(price);
                hfGoods.setProductNo(productNo);
                hfGoods.setVideoLink(goodVideoSrc);
                Demo saveHfGoodsDataDemo = new Demo();
                saveHfGoodsDataDemo.saveHfGoodsData(hfGoods);

                Demo hfGoodIdDemo = new Demo();
                long hfGoodId = hfGoodIdDemo.getHfGoodsHfUid(taobaoGoodId);
                System.out.println("hfGoods保存成功以后产生的id==>" + hfGoodId);
                HfGoodDescription hfGoodDescription = new HfGoodDescription();
                hfGoodDescription.setGoodInfo(goodDetailHTML);
                hfGoodDescription.setHfGoodId(hfGoodId);
                hfGoodDescription.setAttributes("<ul class=\"list\">" + htmlAttributes + "</ul>");
                hfGoodDescription.setTaobaoGoodId(hfGoods.getTaoBaoGoodId());
                Demo saveGoodInfoDataDemo = new Demo();
                saveGoodInfoDataDemo.saveGoodInfoData(hfGoodDescription);
                // driver.close();
            }
        }
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
}
